package com.hyou.demos.mybatis.advice;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.hyou.demos.mybatis.base.CommonMessage;
import com.hyou.demos.mybatis.utils.JsonUtil;

@ControllerAdvice
public class ControllerExceptionHandler {
    
    private static final Logger log = LoggerFactory.getLogger(ControllerExceptionHandler.class);
    
    @ExceptionHandler(Exception.class)
    public String exception(HttpServletResponse response, Exception e) {
        log.error(e.getMessage(), e);
        
        CommonMessage msg = new CommonMessage(false, e.getMessage());
        printJsonMsg(response, msg);
        
        return null;
    }
    
    public void printJsonMsg(HttpServletResponse res, Object dataObject) {
        res.setContentType("text/json;charset=UTF-8");

        String jsonStr = JsonUtil.writeValueAsString(dataObject);

        PrintWriter out = null;

        try {
            out = res.getWriter();
            out.write(jsonStr);
        } catch (IOException ioe) {
            log.error(ioe.getMessage(), ioe);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (out != null) {
                out.flush();
                out.close();
            }
        }
    }
    
}
